import { usePermissionStore } from '@/stores/permission'
import { toArray } from '@/utils/object'
import type { Directive, VNode } from 'vue'

type Target = HTMLElement
type Value = string | string[]

const handleAuth = (el: Target, value: Value) => {
  const permissionStore = usePermissionStore()
  el.style.display = permissionStore.hasPermission(toArray(value)) ? '' : 'none'
}

export const auth: Directive<Target, Value> = {
  mounted: (el, { value }) => handleAuth(el, value),
  updated: (el, { value }) => handleAuth(el, value)
}

export const authVNode = (vNode: VNode, auth: Value): VNode | null => {
  const permissionStore = usePermissionStore()
  return !permissionStore.hasPermission(toArray(auth)) ? null : vNode
}
